package com.xinrui.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xinrui.sunnyday.constant.MessageConstant;
import com.xinrui.sunnyday.constant.RedisMessageConstant;
import com.xinrui.sunnyday.entity.Result;
import com.xinrui.sunnyday.pojo.Member;
import com.xinrui.sunnyday.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

@Controller
@ResponseBody
@RequestMapping("/login")
public class LoginController {
    @Reference
    private LoginService loginService;
    @Autowired
    private JedisPool jedisPool;//redis
    @PostMapping("/check")
    public Result check(@RequestBody Map<String,Object> loginInfo, HttpServletResponse res){
//        1.判断验证码是否正确
//        获取电话号码
        Object telephone = loginInfo.get("telephone");
//        将电话号码拼接
        String key = RedisMessageConstant.SENDTYPE_LOGIN + "_" + telephone;
//        创建jedis对象
        Jedis resource = jedisPool.getResource();
        //        查询redis
        String s = resource.get(key);
        if (StringUtils.isEmpty(s)) {
//           等于空则验证码没有
            return new Result(false, "请重新发送验证码");
        }
//        前端传递过来的代码
        Object validateCode = loginInfo.get("validateCode");
//        判断是否一致
        if (!s.equals(validateCode)) {
//            不一致，弹出提示
            return new Result(false, "您输入的验证码有误");
        }
//        2.判断是否是会员
//        根据电话号码查询是否有这个会员，没有自动注册，有则登录成功
        Member member= loginService.findMember(telephone);
        if(null==member){
//            不是会员:添加
            Member  memberOne = new Member();
            //注册的时间
            memberOne.setRegTime(new Date());
            //注册手机号码
            memberOne.setPhoneNumber(String.valueOf(telephone));
            //标记是手机快速注册
            memberOne.setRemark("手机快速注册");
            //7.2添加为新会员
            loginService.add(memberOne);
        }
//        是会员跟踪记录的手机号码
        Cookie cookie = new Cookie("login_member_telephone", String.valueOf(telephone));
//        存储时长: 存1个月
        cookie.setMaxAge(30*24*60*60);
        // 访问的路径
        cookie.setPath("/");
        res.addCookie(cookie);
        return new Result(true, MessageConstant.LOGIN_SUCCESS);
    }
}
